package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	comment := "Go is an open source programming language that makes it easy to build simple, " +
		"reliable,  " +
		"and efficient software."
	basicReader := strings.NewReader(comment)
	fmt.Println("字符串长度:", basicReader.Size())
	size := 64
	reader := bufio.NewReaderSize(basicReader, size)
	fmt.Println("缓冲区长度:", reader.Size())
	// 此时缓冲区还没有被填充
	fmt.Println("缓冲区里的未读字节数：", reader.Buffered())
	fmt.Println()

	peekNum := 41
	bytes, err := reader.Peek(peekNum)
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
	}
	fmt.Printf("Peek读取(%d): %q\n", len(bytes), bytes)
	fmt.Println("缓冲区里的未读字节数：", reader.Buffered())
	fmt.Println()

	// Peek方法不改变已读计数
	// 把上面用Peek方法读取的过程封装一下，反复调用
	peek(reader, 2)
	peek(reader, 5)
	peek(reader, 8)
}

func peek(reader *bufio.Reader, n int) {
	bytes, err := reader.Peek(n)
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
	}
	fmt.Printf("Peek读取(%d): %q\n", len(bytes), bytes)
}
